#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include<cstring>
using namespace std;
void Usage()
{
    cout << "Usage:./server[ip] [port]" << endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
        return 1;
    }
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
    {
        perror("socket");
        return 1;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    addr.sin_port = htons(atoi(argv[2]));

    int ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
    if (ret < 0)
    {
        cout << "bind error" << endl;
        return 1;
    }
    ret = listen(fd, 10);
    if (ret < 0)
    {
        cout << "listen error" << endl;
        return 1;
    }
    while (true)
    {
        struct sockaddr_in client_addr;
        socklen_t len=sizeof(client_addr);
        int client_fd=accept(fd,(struct sockaddr*)&client_addr,&len);
        if(client_fd<0)
        {
            cout<<"accept fail"<<endl;
            continue;
        }
        char input_buf[1024*10]={0};
        ssize_t read_size=read(client_fd,input_buf,sizeof(input_buf));
        if(read_size<0)
        {
            return 1;
        }
        cout<<"[Request]"<<input_buf<<endl;
        char buf[1024]={0};
        const char* hello="<h1>hello,world<h1>";
        sprintf(buf,"HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s",strlen(hello),hello);
        write(client_fd,buf,sizeof(buf));
    }
    return 0;
}